#include <Arduino.h>
#include <stdio.h>
#include <SPI.h>
#include <WiFi.h>
#include <sensorData.h>
#include "pub.h"
#include "allinit.h"
#include "PubSubClient.h"
#include <Ticker.h>
#include "EEPROM.h"
#include "MT.h"
const char *ssid = WiFissid;
const char *password = WiFipassword;
const char *mqttServerIp = MQTTServerIp;
uint16_t mqttServerPort = MQTTServerPort;
extern int mt_flag;     //mt是否自动
int open_flag = 1;  //mt是否打开zhuangt
int close_flag = 0; //mt是否关闭状态
WiFiClient wifiClient;
PubSubClient mqttClient(wifiClient);
Ticker ticker1;
Ticker ticker2;

void connectMQTTserver();
void receiveCallback(char *topic, byte *payload, unsigned int length);
void subscribeTopic();
void connectWifi();
void controler();
//void controller(String flag);
String Payload;

bool sensor_flag;

void callback1()
{

  sensor_display();
}
int addr = 0;
void callback2()
{
  double temp, data;
  double count;
  temp = (long)analogRead(33); // water
  data = (temp / 512) * 10;
  EEPROM.writeDouble(addr, data);
  delay(10);
  Serial.print("the depth is:");
  Serial.print(data);
  Serial.println("mm");

  if (addr <= 60)
  {
    count = EEPROM.readDouble(addr);
    //- EEPROM.readDouble(512-(60-addr));
  }
  if (addr > 60 && addr < 512)
  {
    count = EEPROM.readDouble(addr) - EEPROM.readDouble(addr - 60);
  }

  if (addr == 512)
  {
    addr = 0;
  }
  Serial.println("--------------WATER----------------");
  Serial.println(count);
  Serial.println("--------------WATER----------------");
  httppub(count);
  addr++;
}

void setup()
{
  pinMode(LED_PIN, OUTPUT);   // 设置LED引脚为输出模式
  digitalWrite(LED_PIN, LOW); // 启动后关闭板上LED
  Serial.begin(9600);         // 启动串口通讯
  EEPROM.begin(512);          //启动NVC
  //设置ESP8266工作模式为无线终端模式
  WiFi.mode(WIFI_STA);

  // 连接WiFi
  connectWifi();

  // 设置MQTT服务器和端口号
  mqttClient.setServer(mqttServerIp, mqttServerPort);
  mqttClient.setCallback(receiveCallback);

  // 连接MQTT服务器
  connectMQTTserver();
  sensor_init();
  ticker1.attach(4, callback1);
  ticker2.attach(10, callback2);
}

void loop()
{
  if (mqttClient.connected())
  {                    // 如果开发板成功连接服务器
    mqttClient.loop(); // 处理信息以及心跳
  }
  else
  {                      // 如果开发板未能成功连接服务器
    connectMQTTserver(); // 则尝试连接服务器
  }

  //sensor_display();
  controler();
}

// 连接MQTT服务器并订阅信息
void connectMQTTserver()
{
  // 根据ESP8266的MAC地址生成客户端ID（避免与其它ESP8266的客户端ID重名）
  String clientId = "esp8266-" + WiFi.macAddress();

  // 连接MQTT服务器
  if (mqttClient.connect(clientId.c_str()))
  {
    Serial.println("MQTT Server Connected.");
    Serial.println("Server Address:");
    Serial.println(mqttServerIp);
    Serial.println("ClientId: ");
    Serial.println(clientId);
    subscribeTopic(); // 订阅指定主题
  }
  else
  {
    Serial.print("MQTT Server Connect Failed. Client State:");
    Serial.println(mqttClient.state());
    delay(5000);
  }
}

// 收到信息后的回调函数
void receiveCallback(char *topic, byte *payload, unsigned int length)
{
  Serial.print("Message Received [");
  Serial.print(topic);
  Serial.print("] ");
  for (int i = 0; i < length; i++)
  {

    Payload = Payload + (char)payload[i];
  }
  Serial.println("-----------MQTT-----------");
  Serial.print("Payload :");
  Serial.println(Payload);
  Serial.print("Message Length(Bytes) ");
  Serial.println(length);
  digitalWrite(RGB_B_PIN,LOW);
  delay(100);
  digitalWrite(RGB_B_PIN,HIGH);
}

// 订阅指定主题
void subscribeTopic()
{
  String topicString = MQTT_Topic_1;
  char subTopic[topicString.length() + 1];
  strcpy(subTopic, topicString.c_str());

  // 建立订阅主题2
  String topicString2 = MQTT_Topic_2;
  char subTopic2[topicString2.length() + 1];
  strcpy(subTopic2, topicString2.c_str());

  // 通过串口监视器输出是否成功订阅主题1以及订阅的主题1名称
  if (mqttClient.subscribe(subTopic))
  {
    Serial.println("Subscrib Topic:");
    Serial.println(subTopic);
  }
  else
  {
    Serial.print("Subscribe Fail...");
  }

  // 通过串口监视器输出是否成功订阅主题2以及订阅的主题2名称
  if (mqttClient.subscribe(subTopic2))
  {
    Serial.println("Subscrib Topic:");
    Serial.println(subTopic2);
  }
  else
  {
    Serial.print("Subscribe Fail...");
  }
}

// ESP8266连接wifi
void connectWifi()
{

  //WiFi.begin(ssid, password);
   WiFi.beginSmartConfig();
  //等待WiFi连接,成功连接后输出成功信息
  while (WiFi.status() != WL_CONNECTED)
  {
    delay(1000);
    Serial.print(".");
    WiFi.beginSmartConfig();
  }
  Serial.println("");
  Serial.println("WiFi Connected!");
  Serial.println("");
}

void controler()
{

  if (Payload == "on" && open_flag)
  {

    // 开启mt。

    Payload = "";
    mt_flag = 0;
    mt_play_open();
    open_flag = 0;
    close_flag = 1;

    //digitalWrite(LED_PIN, LOW);
  }
  if (Payload == "off" && close_flag)
  {

    Payload = "";
    mt_flag = 0;
    mt_play_close();
    close_flag = 0;
    open_flag = 1;

    //digitalWrite(LED_PIN, HIGH);
  }
  if (Payload == "blink")
  {
    
    /*
    for (int i = 0; i < 2; i++)
    {
      digitalWrite(LED_PIN, HIGH);
      delay(250);
      digitalWrite(LED_PIN, LOW);
      delay(250);
      digitalWrite(LED_PIN, HIGH);
      delay(250);     
      digitalWrite(LED_PIN, LOW);
    }
    */
    Payload = "";
    mt_flag = 1;
  }
  else
  {
    Payload = "";
  }
}